package cn.jdy.plugins.wap;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.WebSocketSession;

import cn.jdy.authority.entity.Organ;
import cn.jdy.authority.service.OrganService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.HttpUtil;
import cn.jdy.framework.util.JsonUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.News;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Advertising;
import cn.jdy.plugins.entity.CheckLive;
import cn.jdy.plugins.entity.EvaluationProject;
import cn.jdy.plugins.entity.ExamOptions;
import cn.jdy.plugins.entity.ExamQuestions;
import cn.jdy.plugins.entity.Line;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.entity.PptImg;
import cn.jdy.plugins.entity.RelatedVideo;
import cn.jdy.plugins.entity.WatchUser;
import cn.jdy.plugins.entity.WxConfig;
import cn.jdy.plugins.service.AdvertisingService;
import cn.jdy.plugins.service.ApplyCashService;
import cn.jdy.plugins.service.ChatService;
import cn.jdy.plugins.service.CheckLiveService;
import cn.jdy.plugins.service.EvaluationProjectService;
import cn.jdy.plugins.service.ExamOptionsService;
import cn.jdy.plugins.service.ExamQuestionsService;
import cn.jdy.plugins.service.LabelService;
import cn.jdy.plugins.service.LineService;
import cn.jdy.plugins.service.LiveService;
import cn.jdy.plugins.service.PptImgService;
import cn.jdy.plugins.service.RedPacketService;
import cn.jdy.plugins.service.RelatedVideoService;
import cn.jdy.plugins.service.SecretKeyCetService;
import cn.jdy.plugins.service.WatchUserService;
import cn.jdy.plugins.service.WxConfigService;
import cn.jdy.plugins.wap.util.ChatUtil;
import cn.jdy.plugins.wap.util.EmojiFilter;
import cn.jdy.plugins.websocket.WebsocketEndPoint;

/**
 * @title 获取用户信息,调用微信图片接口
 * @author ningqian
 * @since 2017-3-23,2017-4-5
 */

@Controller
@RequestMapping("/fllive")
public class LiveflCtrl extends BaseCtrl {
	@Autowired
	private LiveService liveService;
	@Autowired
	private OrganService organService;
	@Autowired
	private LineService lineService;
	@Autowired
	private WatchUserService watchUserService;
	@Autowired
	private WxConfigService wxConfigService;
	@Autowired
	private ChatService chatService;
	@Autowired
	private AdvertisingService advertisingService;
	@Autowired
	private ConfService confService;
	@Autowired
	private LabelService labelService;
	@Autowired
	private RelatedVideoService relatedVideoService;
	@Autowired
	private ApplyCashService applyCashService;
	@Autowired
	private PptImgService pptImgService;
	@Autowired
	private EvaluationProjectService evaluationProjectService;
	@Autowired
	private ExamOptionsService examOptionsService;
	@Autowired
	private RedPacketService redPacketService;
	@Autowired
	private ExamQuestionsService examQuestionsService;
	@Autowired
	private SecretKeyCetService secretKeyCetService;
	@Autowired
	private CheckLiveService checkLiveService;
	private static Long liveId;
	private static String url; // 链接地址
	private static String scope; // 以snsapi_base为scope静默授权,以snsapi_userinfo为scope手动授权
	private static String appid; // 公众号的唯一标识
	private static String secret; // 公众号的appsecret
	private static String mchid; // 商户号
	private static String apikey; // 支付秘钥

	/**
	 * 进入直播首页 授权
	 * 
	 * @param id
	 *            直播id
	 * @return
	 */
	@RequestMapping("/index/{id}")
	public String index(@PathVariable Long id) {
		liveId = id;
		// String urls="http://zb.qwe.com.cn:8080/w/live/index/12";
		/*		String urls = request.getRequestURL().toString();
		if (urls.contains(":8080")) {
			urls = urls.replaceAll(":8080", "");
		}

		url = urls.split("index")[0] + "toChat";*/
		
		String urls = request.getHeader("Host2") ;
		if (urls.contains(":8080")) {
			url = urls.replaceAll(":8080", "");
		}else{
			url=urls;
		}
		url="http://"+url+ "/w/live/toChat";
		// url="http://zb.qwe.com.cn/w/live/"+"toChat";
		BaseLog.e(this.getClass(), "回调地址" + url);
		String cdurl = URLEncoder.encode(url);
		// 获取直播明细
		Live live = liveService.find(liveId);
		if (null != live) {
			// 获取线路信息
			Line line = lineService.find(live.getMainid());
			// 获取机构信息中的appid，appsecret
			Organ weixin = organService.find(line.getOrganid());
			appid = weixin.getAppId();
			secret = weixin.getAppSecret();
			mchid = weixin.getMchid();
			apikey = weixin.getApikey();

			// 是否强制关注 0 是 -snsapi_base静默授权， 1否-snsapi_userinfo用户手动授权
			// String attention = live.getAttention();
			String attention = "1"; // 静默授权必须关注公众号
			if ("1".equals(attention)) {
				scope = "snsapi_userinfo";
				return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="
						+ appid
						+ "&redirect_uri="
						+ cdurl
						+ "&response_type=code&scope="
						+ scope
						+ "&state=STATE#wechat_redirect";
			} else {
				scope = "snsapi_base";
				return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="
						+ appid
						+ "&redirect_uri="
						+ cdurl
						+ "&response_type=code&scope="
						+ scope
						+ "&state=123#wechat_redirect";
			}

		} else {
			// 跳转到错误界面
			BaseLog.i(this.getClass(), "获取直播明细失败！");
			String errorUrl = request.getRequestURL().toString().split("index")[0]
					+ "toError";
			return "redirect:" + errorUrl;
		}

	}
	@RequestMapping("/addUser")
	@ResponseBody
	public Map<String, Object> addUser(Long liveid,String userOpenId,String userNickName,String userHeadImg,String userSex,String userCity,String userProvince,String userCountry) {
		WatchUser user = watchUserService.findOne("userOpenId",userOpenId);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		//过滤表情
		EmojiFilter  ef=new EmojiFilter();
		userNickName=ef.filterEmoji(userNickName);
		
		int co=0;
		if (user==null) {
			user = new WatchUser();
			user.setLiveId(liveid);
			user.setUserOpenId(userOpenId);
	
			user.setUserNickName(userNickName);
			user.setUserSex(userSex);
			user.setUserHeadImg(userHeadImg);
			user.setUserCity(userCity);
			user.setUserProvince(userProvince);
			user.setUserCountry(userCountry);
			user.setCreateTime(DateUtil
					.getCurrentDate(DateUtil._DEFAULT2));
			try {
				watchUserService.save(user);
				co=1;
		} catch (Exception e) {
			co=0;
		}
		
		}else{
			user.setLiveId(liveid);
			user.setUserOpenId(userOpenId);
	
			user.setUserNickName(userNickName);
			user.setUserSex(userSex);
			user.setUserHeadImg(userHeadImg);
			user.setUserCity(userCity);
			user.setUserProvince(userProvince);
			user.setUserCountry(userCountry);
			user.setUpdateTime(DateUtil
					.getCurrentDate(DateUtil._DEFAULT2));
			try {
				watchUserService.update(user);
				co=1;
		} catch (Exception e) {
			co=0;
		}
	
			}
		jsonMap.put("msg", co);
		return jsonMap;
	}
	/**
	 * 新增或修改用户信息
	 * 	
	 * @RequestMapping("/toChat")
	 * 	public ModelAndView toChat(Long liveid,String userOpenId,String userNickName,String userHeadImg,String userSex,String userCity,String userProvince,String userCountry) {

	public ModelAndView toChat(Long liveid,String openid) {
		ModelAndView mv = new ModelAndView();
		// 获取用户基本信息
		Map<String, Object> watchUser = new HashMap<String, Object>();
		try {
			if (null != openid && !"".equals(openid)) { // code不为空
				watchUser = toUser(openid);
				// BaseLog.i(this.getClass(), "当前返回用户size："+watchUser.size());
				if (null != watchUser && 0 < watchUser.size()) {
					String userOpenId = watchUser.get("openid").toString();
					String userNickName = watchUser.get("nickname").toString();
					String userSex = watchUser.get("gender").toString(); // 0-未知,1-男,2-女
					String userHeadImg = watchUser.get("avatar").toString();
					String userCity = watchUser.get("residecity").toString();
					String userProvince = watchUser.get("resideprovince").toString();
					String userCountry = watchUser.get("nationality").toString();
					// String subscribe = watchUser.get("subscribe").toString();
					// //用户是否已关注公众号
					watchUser.put("openid", userOpenId);
					watchUser.put("headimgurl", userHeadImg);
					watchUser.put("sex", userSex);
					watchUser.put("city", userCity);
					watchUser.put("province", userProvince);
					watchUser.put("country", userCountry);
	 * 
	 * @return
	 */
	@RequestMapping("/toChat")
	public ModelAndView toChat(Long liveid,String openid) {
		ModelAndView mv = new ModelAndView();
		// 获取用户基本信息
		Map<String, Object> watchUser = new HashMap<String, Object>();
		try {
			if (null != openid && !"".equals(openid)) { // code不为空
		
					
					WatchUser user = watchUserService.findOne("userOpenId",openid);
					watchUser.put("openid",user.getUserOpenId());
					watchUser.put("headimgurl", user.getUserHeadImg());
					watchUser.put("sex", user.getUserSex());
					watchUser.put("city", user.getUserCity());
					watchUser.put("province",user.getUserProvince());
					watchUser.put("country", user.getUserCountry());
					watchUser.put("nickname", user.getUserNickName());
					Live live = liveService.find(liveid);
					if (null != live) {
						// 获取线路信息
						Line line = lineService.find(live.getMainid());
						// 获取机构信息中的appid，appsecret
						Organ weixin = organService.find(line.getOrganid());
						appid = weixin.getAppId();
						secret = weixin.getAppSecret();
						mchid = weixin.getMchid();
						apikey = weixin.getApikey();
					}
			 

					// 1.将用户信息以及直播id放入session中
					watchUser.put("liveId", liveid);
					watchUser.put("appid", appid);
					watchUser.put("mchid", mchid);
					watchUser.put("apikey", apikey);
					session.setAttribute("watchUser", watchUser);
					BaseLog.e(this.getClass(), "获取用户信息成功，并存入session........");

					WebsocketEndPoint wp=new WebsocketEndPoint();
				
				
					
					if (null != live && !StringUtil.isNullOrEmpty(live.getAdurl())) { // 存在广告则进入广告页面
						mv.addObject("data", live);
						mv.setViewName(super.t + "/ads.jsp");
					} else { // 不存在则直接进入直播界面
						
						if (null != watchUser && 0 < watchUser.size()) {
							// 2.获取直播描述以及交流总数
						///	Live live = liveService.find(currentliveId);
							mv.addObject("data", live); // 直播信息
							mv.addObject("labeldata", labelService.querySiteMap(liveid)); // 获取页签
							
							
							List<Map<String, Object>> blist=labelService.queryLiveMap(liveid);
							for (int i = 0; i < blist.size(); i++) {
								 long labelid=((BigInteger) blist.get(i).get("labelid")).longValue();
								if(9889==labelid){
									mv.addObject("addata2", advertisingService.find("liveId", liveid,
											"advertisingType", "2"));// 交流广告
								}
								if(9890==labelid){
									mv.addObject("addata1", advertisingService.find("liveId", liveid,
											"advertisingType", "1"));// 合作广告
								}
								if(9904==labelid){
									DetachedCriteria dc = DetachedCriteria.forClass(Advertising.class);
								  
									
									mv.addObject("gzata1",advertisingService.find("liveId", liveid,
											"advertisingType", "3"));// 合作广告2
								}
							}
							
							
					
							if(live.getIspay()!=null&&live.getIspay().equals("1")){
								mv.addObject("sumzf", redPacketService.find("liveId", liveid,
										"userOpenId", watchUser.get("openid")+"","sendStatus","1","rpType","3").size());// 判断是否交钱
							}else if(live.getIspay()!=null&&live.getIspay().equals("2")){
								mv.addObject("ismiyao", secretKeyCetService.find("liveId", liveid,
										"userOpenId", watchUser.get("openid")+"","isStatus","1").size());// 判断秘钥正确
							}else if(live.getIspay()!=null&&live.getIspay().equals("3")){
								List<CheckLive> list= checkLiveService.find("liveId", liveid,
										"userOpenId", watchUser.get("openid")+"");
							if(list.size()>0){
								mv.addObject("isshenhe", list.get(0).getSendStatus());// 当前审核状态
							}else{
								mv.addObject("isshenhe", "4");// 当前审核状态

							}
							
						}
					
							for (int i = 0; i < blist.size(); i++) {
								//
								   long labelid=((BigInteger) blist.get(i).get("labelid")).longValue();;
							
							}
							
							// 相关视频开始
							String s = live.getCurrentStatus();
							String liveids = "";
							if (s != null && s != "") {
								liveids = s.substring(0, s.length() - 1);
							} else {
								liveids = "0";
							}
							mv.addObject("videodata", liveService.querySiteMap(liveids)); // 相关视频
							mv.setViewName("/flindex.jsp");

						} else { 
							// 重新获取用户信息
						
							mv.setViewName("redirect:/fllive/toError");
						}
				
					}
					}
					return mv;
		
			
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "网页授权异常！", e);
			// 返回错误页面
			mv.setViewName("redirect:/fllive/toError");
			return mv;
		}
	

	}


	@RequestMapping("/forFrame")
	public ModelAndView forFrame(Long liveid,String openid) {
		ModelAndView mv = new ModelAndView("/iframe.jsp");
		mv.addObject("liveid", liveid);
		mv.addObject("openid", openid);
		return mv;
	}
 

	@RequestMapping("/guanzhu")
	public ModelAndView guanzhu() {
		ModelAndView mv = new ModelAndView("/guanzhu.jsp");

		return mv;
	}

	/**
	 * 三秒广告
	 * 
	 */
	@RequestMapping("/adsToIndex")
	public ModelAndView adsToIndex(Long currentliveId) {
		ModelAndView mv = new ModelAndView();
		Live live = liveService.find(currentliveId);
		if (null != live && !StringUtil.isNullOrEmpty(live.getAdurl())) { // 存在广告则进入广告页面
			mv.addObject("data", live);
			mv.setViewName(super.t + "/ads.jsp");
		} else { // 不存在则直接进入直播界面
			mv.setViewName("redirect:/fllive/toIndex/" + currentliveId);
		}

		return mv;
	}

	@SuppressWarnings("static-access")
	@RequestMapping("toIndex/{currentliveId}")
	public ModelAndView toIndex(@PathVariable Long currentliveId) {
		ModelAndView mv = new ModelAndView(super.t + "/flindex.jsp");
		Map<String, Object> watchUser = (Map<String, Object>) session
				.getAttribute("watchUser");
		BaseLog.e(this.getClass(), "当前直播id:" + currentliveId);
		if (null != watchUser && 0 < watchUser.size()) {
			// 2.获取直播描述以及交流总数
			Live live = liveService.find(currentliveId);
			mv.addObject("data", live); // 直播信息
			mv.addObject("labeldata", labelService.querySiteMap(currentliveId)); // 获取页签
			
			
			List<Map<String, Object>> blist=labelService.queryLiveMap(currentliveId);
			for (int i = 0; i < blist.size(); i++) {
				 long labelid=((BigInteger) blist.get(i).get("labelid")).longValue();
				if(9889==labelid){
					mv.addObject("addata2", advertisingService.find("liveId", currentliveId,
							"advertisingType", "2"));// 交流广告
				}
				if(9890==labelid){
					mv.addObject("addata1", advertisingService.find("liveId", currentliveId,
							"advertisingType", "1"));// 合作广告
				}
				if(9904==labelid){
					DetachedCriteria dc = DetachedCriteria.forClass(Advertising.class);
				  
					
					mv.addObject("gzata1",advertisingService.find("liveId", currentliveId,
							"advertisingType", "3"));// 合作广告2
				}
			}
			
			
	
			if(live.getIspay()!=null&&live.getIspay().equals("1")){
				mv.addObject("sumzf", redPacketService.find("liveId", currentliveId,
						"userOpenId", watchUser.get("openid")+"","sendStatus","1","rpType","3").size());// 判断是否交钱
			}else if(live.getIspay()!=null&&live.getIspay().equals("2")){
				mv.addObject("ismiyao", secretKeyCetService.find("liveId", currentliveId,
						"userOpenId", watchUser.get("openid")+"","isStatus","1").size());// 判断秘钥正确
			}else if(live.getIspay()!=null&&live.getIspay().equals("3")){
				List<CheckLive> list= checkLiveService.find("liveId", currentliveId,
						"userOpenId", watchUser.get("openid")+"");
			if(list.size()>0){
				mv.addObject("isshenhe", list.get(0).getSendStatus());// 当前审核状态
			}else{
				mv.addObject("isshenhe", "4");// 当前审核状态

			}
			
		}
	
			for (int i = 0; i < blist.size(); i++) {
				//
				   long labelid=((BigInteger) blist.get(i).get("labelid")).longValue();;
			
			}
			
			// 相关视频开始
			String s = live.getCurrentStatus();
			String liveids = "";
			if (s != null && s != "") {
				liveids = s.substring(0, s.length() - 1);
			} else {
				liveids = "0";
			}
			mv.addObject("videodata", liveService.querySiteMap(liveids)); // 相关视频

		} else { 
		//	BaseLog.e(this.getClass(), "哦批openid=redirect:/fllive/toChat?liveid="+currentliveId+"&userOpenId="+watchUser.get("openid")+"&userNickName="+watchUser.get("nickname")+"&userHeadImg="+watchUser.get("headimgurl")+"&userSex="+watchUser.get("sex")+"&userCity="+watchUser.get("city")+"&userProvince="+watchUser.get("province")+"&country="+watchUser.get("country")+"");
			// 重新获取用户信息
			//http://www.bee-live.cn/w/fllive/toChat?liveid=3035&userOpenId=oqkKrxIL9dtS52cA7jozxufed8q4&userNickName=市井小民&userHeadImg=http://wx.qlogo.cn/mmopen/Fxv450XibIyfMicQVvI4QHwclyzRAHDmJdWKtJVDNZ9BVkexyUYicw0Uo76IASVcn9NgIibs3ATOoyYricnHs5Csy7EdbIFZuVbmc/0&userSex=1&userCity=武汉&userProvince=湖北&userCountry=中国
		
			mv.setViewName("redirect:/fllive/toChat?liveid="+currentliveId+"&openid="+watchUser.get("openid")+"");
		}
		return mv;
	}
	
	/**
	 * 获取法律微云接口里面的用户信息
	 * 
	 * @param
	 * @return
	 */
	public Map<String, Object> toUser(String openid) {
		@SuppressWarnings("unused")
		Map<String, Object> jsonMap = new HashMap<String, Object>();
	
	
		try {
			// 根据code 得到 openid
			String vre = HttpUtil.sendGet("http:/www.iyunfa.cn/app/index.php?i=102&c=entry&do=GetUser&m=zhibo&openid="+openid ,"UTF-8");
			jsonMap = (HashMap<String, Object>) JsonUtil
					.toObj(vre, Map.class);

				BaseLog.i(this.getClass(), jsonMap + ">>>>>.>>>>>user");
				// System.out.println(oep + ">>>>>.>>>>>user ");
		
		} catch (IOException e) {
			e.printStackTrace();
			BaseLog.e(this.getClass(), "获取用户信息失败！", e);
		}

		return jsonMap;
		
	}

	/**
	 * 微信图片接口：1.据票据调用微信官方接口，获取微信签名
	 * 
	 * @param url
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */
	@RequestMapping("/getConfigInfo")
	@ResponseBody
	public Map<String, Object> getConfigInfo(HttpServletRequest request)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String ticket = null;
		String token = null;
		BaseLog.e(this.getClass(), "当前appid：" + appid + ",appsecret:" + secret);
		try {
			// 获取当前时间毫秒-- 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
			Date date = new Date();
			long currentTime = date.getTime();
			// System.out.println(currentTime);

			// 1.判断库中是否存在ticket
			WxConfig wxConfig = wxConfigService.findOne("type", "1", "appid",
					appid);
			if (null != wxConfig
					&& StringUtil.isNotEmpty(wxConfig.getJsapi_ticket())) {
				// 2、判断ticket是否过期,未过期则直接使用当前ticket
				if (currentTime < wxConfig.getTicketTime()) {
					ticket = wxConfig.getJsapi_ticket();
					
					BaseLog.i(this.getClass(), "当前存在ticket：" + ticket);
				} else {// 3、ticket过期,获取token判断token是否过期
					if (StringUtil.isNotEmpty(wxConfig.getAccess_token())) {
						if (currentTime < wxConfig.getTokenTime()) {
							token = wxConfig.getAccess_token();
						}
					}
					ticket = getTicket(token, appid, secret);
					BaseLog.i(this.getClass(), "当前ticket过期，重新获取ticket："
							+ ticket);
				}

			} else { // 不存在则直接调用接口获取
				ticket = getTicket(token, appid, secret);
				BaseLog.i(this.getClass(), "当前不存在ticket，获取ticket：" + ticket);
			}

			String noncestr = ChatUtil.create_nonce_str();
			String timestamp = ChatUtil.create_timestamp();
			String url = request.getHeader("Referer");
			String signature = "";

			if (ticket != null) {
				StringBuilder sb = new StringBuilder("jsapi_ticket=");
				sb.append(ticket).append("&noncestr=").append(noncestr)
						.append("&timestamp=").append(timestamp)
						.append("&url=").append(url);

				try {
					// 对接后的字符串进行sha1加密
					MessageDigest md = MessageDigest.getInstance("SHA-1");
					md.reset();
					md.update(sb.toString().getBytes("UTF-8"));
					signature = ChatUtil.byteToHex(md.digest());
					map.put("jsapi_ticket", ticket);
					map.put("appId", appid);
					map.put("timestamp", timestamp);
					map.put("nonceStr", noncestr);
					map.put("signature", signature);
					map.put("originalStr", sb.toString());
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				// System.out.println("生成的签名"+signature);
				BaseLog.e(this.getClass(), "生成签名：" + signature);
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			BaseLog.e(this.getClass(), "获取微信签名失败！", e);
		}

		return map;

	}

	/**
	 * 将微信图片服务器上的图片下载到本地
	 * 
	 * @param media_id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getPhoto")
	@ResponseBody
	public Map<String, Object> getPhoto(
			@RequestParam("media_id") String media_id,String token) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		// http请求方式: GET,https调用
		// var url =
		// "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		String fileRoot = "/upload";
		String filePath = null;
		String returnPath = null;
		try {

			// 获取当前时间毫秒-- 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
			Date date = new Date();
			long currentTime = date.getTime();
			System.out.println(currentTime);

			// 1.判断库中是否存在access_token
		/*	WxConfig wxConfig = wxConfigService.findOne("type", "1", "appid",
					appid);
			if (null != wxConfig
					&& StringUtil.isNotEmpty(wxConfig.getAccess_token())) {
				if (currentTime < wxConfig.getTokenTime()) {
					token = wxConfig.getAccess_token();
				} else {
					token = getAccess_token(appid, secret);
				}
			} else {
				token = getAccess_token(appid, secret);
			}*/

			String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="
					+ token + "&media_id=" + media_id;
			BaseLog.e(this.getClass(), "下载图片地址：" + requestUrl);
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");

			// 本地服务器图片存放地址

			String path = request.getSession().getServletContext()
					.getRealPath("/");
			SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
			String newfileDir = formater.format(new Date());
			String savePath = new File(path).getParent() + fileRoot + "/"
					+ "confPic" + "/" + newfileDir;

			if (!savePath.endsWith("/")) {
				savePath += "/";
			}

			// 根据内容类型获取扩展名
			// String fileExt =
			// getFileexpandedName(conn.getHeaderField("Content-Type"));
			// BaseLog.e(LiveCtrl.class, "获取到图片扩展名:"+fileExt);
			String fileExt = ".jpg";
			// 将mediaId作为文件名
			filePath = savePath + media_id + fileExt;

			// 返回到页面的图片路径
			returnPath = fileRoot + "/" + "confPic" + "/" + newfileDir + "/"
					+ media_id + fileExt;

			File dir = new File(savePath);
			if (!dir.exists()) {
				FileUtils.forceMkdir(dir);
			}

			BufferedInputStream bis = new BufferedInputStream(
					conn.getInputStream());
			FileOutputStream fos = new FileOutputStream(new File(filePath));
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);
			fos.close();
			bis.close();

			conn.disconnect();
			String info = String.format("下载媒体文件成功，filePath=" + filePath);
			System.out.println(info);

		} catch (Exception e) {
			e.printStackTrace();
			BaseLog.e(this.getClass(), "下载图片到本地服务器失败！", e);
		}

		map.put("filePath", returnPath);
		// 返回图片路径
		return map;
	}

	/**
	 * 根据内容类型判断文件扩展名
	 * 
	 * @param contentType
	 *            内容类型
	 * @return
	 */
	public static String getFileexpandedName(String contentType) {
		String fileEndWitsh = "";
		if ("image/jpeg".equals(contentType))
			fileEndWitsh = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileEndWitsh = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileEndWitsh = ".amr";
		else if ("video/mp4".equals(contentType))
			fileEndWitsh = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileEndWitsh = ".mp4";
		return fileEndWitsh;
	}

	/**
	 * 1.获取令牌access_token
	 * 
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	public String getAccess_token(String app_id, String app_secret)
			throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String access_token = null;
		long expires_in = 0;
		try {
			// 获取当前时间毫秒-- 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
			Date date = new Date();
			long addTime = date.getTime();
			System.out.println(addTime);

			// 微信令牌请求网址(由微信提供)
			String token = HttpUtil.sendGet(
					"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
							+ app_id + "&secret=" + app_secret, "UTF-8");
			HashMap<String, Object> map2 = (HashMap<String, Object>) JsonUtil
					.toObj(token, Map.class);

			if (map2.containsKey("access_token")) {
				access_token = map2.get("access_token").toString();
				expires_in = Long.valueOf(map2.get("expires_in").toString()); // 有效时间
				long e_time = expires_in * 1000; // 转为毫秒

				// 将令牌及有效期存入数据库
				WxConfig wxConfig = wxConfigService.findOne("type", "1",
						"appid", app_id);
				if (null != wxConfig) {
					wxConfig.setAccess_token(access_token);
					wxConfig.setTokenTime(addTime + e_time);
					wxConfigService.update(wxConfig);

				} else {
					wxConfig = new WxConfig();
					wxConfig.setAppid(app_id);
					wxConfig.setType("1");
					wxConfig.setAccess_token(access_token);
					wxConfig.setTokenTime(addTime + e_time);
					wxConfigService.save(wxConfig);
				}
			}
			BaseLog.e(LiveCtrl.class, "获取到access_token：" + token);
		} catch (Exception e) {
			e.printStackTrace();
			BaseLog.e(LiveCtrl.class, "获取access_token失败！", e);
		}

		return access_token;
	}

	/**
	 * 2.根据令牌获取调用微信的票据jsapi_ticket
	 * jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下，jsapi_ticket的有效期为7200秒
	 * ，通过access_token来获取。
	 * 
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public String getTicket(String accessToken, String app_id, String app_secret)
			throws Exception {
		String ticket = null;
		long expires_in = 0;
		try {
			// 获取accesstoken
			if (StringUtil.isEmpty(accessToken)) {
				accessToken = getAccess_token(app_id, app_secret);
			}

			// 获取当前时间毫秒-- 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
			Date date = new Date();
			long addTime = date.getTime();
			System.out.println(addTime);
			// 获取票据的网址(由微信提供)
			String tickets = HttpUtil.sendGet(
					"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
							+ accessToken + "&type=jsapi", "UTF-8");
			HashMap<String, Object> map2 = (HashMap<String, Object>) JsonUtil
					.toObj(tickets, Map.class);

			if (map2.containsKey("ticket")) {
				ticket = map2.get("ticket").toString();
				expires_in = Long.valueOf(map2.get("expires_in").toString()); // 有效时间
				long e_time = expires_in * 1000; // 转为毫秒
				// 将票据及有效期存入数据库
				WxConfig wxConfig = wxConfigService.findOne("type", "1",
						"appid", app_id);
				if (null != wxConfig) {
					wxConfig.setJsapi_ticket(ticket);
					wxConfig.setTicketTime(addTime + e_time);
					wxConfigService.update(wxConfig);
				}
			}
			BaseLog.e(LiveCtrl.class, "获取jsapi_ticket:" + ticket);
		} catch (Exception e) {
			e.printStackTrace();
			BaseLog.e(LiveCtrl.class, "获取jsapi_ticket失败！", e);
		}

		return ticket;
	}

	/**
	 * 点击次数,用来记录当前视频的总观看人数。
	 * 
	 * @author lph
	 * @param
	 * @return
	 */
	@RequestMapping("/updateNumber")
	@ResponseBody
	public Map<String, Object> updateNumber(Long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			RelatedVideo relatedVideo = relatedVideoService.find(id);
			int nuber = 0;
			if (relatedVideo != null) {
				if (relatedVideo.getWatchNumber() == null) {
					nuber = 0;
				} else {
					nuber = relatedVideo.getWatchNumber();
				}
				relatedVideo.setWatchNumber(nuber + 1);
				relatedVideo.setUpdateTime(DateUtil
						.getCurrentDate(DateUtil._DEFAULT2));
				relatedVideoService.update(relatedVideo);
			} else {

			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "修改异常", e);
		}
		return jsonMap;
	}

	@SuppressWarnings("static-access")
	@RequestMapping("toError")
	public ModelAndView toError() {
		ModelAndView mv = new ModelAndView(super.t + "/error.jsp");
		return mv;
	}
	

}
